<template>
  <UiFilterGroup class="collection-sorter">
    <UiFilter
      v-for="[property, isAscending] in activeSorts"
      :key="property"
      @edit="emit('toggleSortDirection', property)"
      @remove="emit('removeSort', property)"
    >
      <span class="property">
        <VtsIcon :name="isAscending ? 'fa:caret-up' : 'fa:caret-down'" size="medium" />
        {{ property }}
      </span>
    </UiFilter>

    <UiActionButton icon="fa:plus" class="add-sort" @click="openFormModal()">
      {{ t('add-sort') }}
    </UiActionButton>
  </UiFilterGroup>
</template>

<script lang="ts" setup generic="TProperty extends PropertyKey">
import UiActionButton from '@/components/ui/UiActionButton.vue'
import UiFilter from '@/components/ui/UiFilter.vue'
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
import type { ActiveSorts, Sorts } from '@/types/sort'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import { useModal } from '@core/packages/modal/use-modal.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

const { availableSorts } = defineProps<{
  availableSorts: Sorts
  activeSorts: ActiveSorts<Record<TProperty, any>>
}>()

const emit = defineEmits<{
  toggleSortDirection: [property: TProperty]
  addSort: [property: TProperty, isAscending: boolean]
  removeSort: [property: TProperty]
}>()

const { t } = useI18n()

const openFormModal = useModal({
  component: import('@/components/modals/CollectionSorterModal.vue'),
  props: { availableSorts: computed(() => availableSorts) },
  onConfirm: ({ property, isAscending }) => emit('addSort', property as TProperty, isAscending),
})
</script>

<style lang="postcss" scoped>
.property {
  display: inline-flex;
  align-items: center;
  gap: 0.7rem;
}
</style>
